package thread;

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
 * @Author Janson
 * @Date 2022/2/24 12:32
 * @Version 1.0
 */
public class TestThreadDownlPic extends Thread {
    private String name;
    private String url;
    //构造方法，调用的时候用于传递初始参数
    public TestThreadDownlPic(String url,String name) {
        this.name = name;
        this.url = url;
    }
    //重写run方法
    @Override
    public void run(){
        //下载图片的线程的执行体
        WebDownload webDownload = new WebDownload();
        webDownload.downloader(url,name);
        System.out.println("下载了文件名为：" + name);
    }
    //主线程 main 方法
    public static void main(String[] args) {
        //创建 线程 对象
        TestThreadDownlPic testThreadDownlPic1 = new TestThreadDownlPic(
                "https://www.todesk.com/image/download/windows_pic.png",
                //C:\Users\25393\Desktop\img\  该地址为路径，1.jpg为文件名
                "C:\\Users\\25393\\Desktop\\img\\1.jpg");
        //如果不写路径，则默认在项目根路径下
        TestThreadDownlPic testThreadDownlPic2 = new TestThreadDownlPic(
                "https://www.todesk.com/image/logo-text.png",
                "2.jpg");
        TestThreadDownlPic testThreadDownlPic3 = new TestThreadDownlPic(
                "https://www.todesk.com/image/news/1.jpg",
                "3.jpg");
        //启动线程
        testThreadDownlPic1.start();
        testThreadDownlPic2.start();
        testThreadDownlPic3.start();
    }

}
//下载图片的类
class WebDownload{
    public void downloader(String url,String name){
        try {
            //借助 commons io 包中的 FileUtils 类的 copyURLToFile方法进行 下载 图片
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("执行webdownload类，出现io异常。");
        }
    }
}